package com.lagou.common.rpc;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.charset.Charset;

public class JsonEncoder extends MessageToByteEncoder<Object> {

    private final Charset charset;

    public JsonEncoder() {
        this(Charset.defaultCharset());
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        byte[] bytes = JSON.toJSONString(o).getBytes();
        byteBuf.writeBytes(bytes);
    }

    public JsonEncoder(Charset charset) {
        if (charset == null) {
            throw new NullPointerException("charset");
        } else {
            this.charset = charset;
        }
    }


}
